package com.hmdp.controller;


import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("list")
    public Result queryTypeList() {
        //添加到redis缓存中

        //1.先去redis中查找有没有对应的数据
        String shopType = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_TYPE_KEY);


        if (shopType!= null) {
 List<ShopType> shopTypeList = JSONUtil.toList(shopType, ShopType.class);

                    //2.如果有，直接返回
                    return Result.ok(shopTypeList);
                }

        //3.如果没有，去数据库中查找
        List<ShopType> list = typeService.query().orderByAsc("sort").list();

        //4.如果没有，返回错误
        if (list == null) {
            return Result.fail("数据不存在！");
        }else {

            //5.如果有，存入redis中
            String shopTypeList = JSONUtil.toJsonStr(list);
            stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_TYPE_KEY,shopTypeList,300, TimeUnit.MINUTES);

/*            list.stream().forEach(shopTypeDb -> {
                stringRedisTemplate.opsForHash().putAll(RedisConstants.SHOP_TYPE_KEY.concat(shopTypeDb.getId().toString()),
                        BeanUtil.beanToMap(shopTypeDb,new HashMap<>(),
                                CopyOptions.create().setIgnoreNullValue(true).
                                setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())));
                    });*/

            //6.返回
            return Result.ok(list);
        }

    }
}
